import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/userInfo";
import router from "@/router/index.js";

const service = axios.create({
	baseURL: "open",
	timeout: 60000, // 过期时间
});
export const service2 = axios.create({
	baseURL: "open",
	timeout: 60000, // 过期时间
});
// request interceptor
service.interceptors.request.use(
	(config) => {
		// 发送请求之前做的
		// const token = !store.getters.token ? sessionStorage.getItem('token') : store.getters.token;
		// if (token) {
		//   config.headers['Authori-zation'] = token;
		// }
		let token = localStorage.getItem("token");
		if (token) {
			config.headers.Authorization = token;
		}
		if (/get/i.test(config.method)) {
			config.params = config.params || {};
			config.params.temp = Date.parse(new Date()) / 1000;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	(response) => {
		const res = response;
		if (res.data.code === 401) {
			const store = useUserStore();
			store.$reset();
			// localStorage.clear();
			ElMessage.error("请登录");
			router.push("/login");
		} else if (res.data.code && res.data.code !== 200) {
			ElMessage.error(res.data.msg);
		}

		return res.data;
	},
	(error) => {
		// Message({
		// 	message: error.message,
		// 	type: "error",
		// 	duration: 5 * 1000,
		// });

		return Promise.reject(error);
	}
);

export default service;
